package com.woniu.map.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.internalcommon.dto.POIType;
import com.woniu.map.mapper.POITypeMapper;
import com.woniu.map.service.POITypeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class POITypeServiceImpl implements POITypeService {
    @Resource
    private POITypeMapper poiTypeMapper;
    @Autowired
    private RedisTemplate<String, List<String>> redisTemplate;


    /**
     * 获取POI类型列表
     * @param level  cacheable key 映射不到level
     * @return
     */
    @Override
    @Cacheable(value = "POITypeList", key = "'level='+#p0", unless = "#result == null")
    public List<POIType> getPOITypeListByLevel(String level) {
        try {
            //
         return poiTypeMapper.selectList(
                 new QueryWrapper<POIType>().eq("type_level", 1));
        }catch (Exception e){
             log.info("POITypeServiceImpl.getPOITypeListByLevel error");
             return null;
        }
    }

    /**
     * 查子poi
     * @param parentCode 父级代码
     * @param level  级 一般为2 或 3
     * @return
     */
    @Override
    @Cacheable(cacheNames = "POITypeList", key = "#p0+ ':' + #p1")
    public List<POIType> getPOITypeListByParentCode(String parentCode, String level) {

        try {
            return poiTypeMapper.selectList(
                    new QueryWrapper<POIType>()
                            .eq("parent_code", parentCode)
                            .eq("type_level", level));
        }catch (Exception e){
            log.info("POITypeServiceImpl.getPOITypeListByParentCode error");
            return null;
        }
    }

    // 查询所有类型名
    @Override
//    @Cacheable("POITypeNames")
    public List<String> getAllPOITypeNames() {
        List<String> poiTypeNames = redisTemplate.opsForValue().get("POITypeNames");
        if (poiTypeNames != null && poiTypeNames.size() > 0){
            return  poiTypeNames;
        }
        List<String> name = poiTypeMapper.selectList(new QueryWrapper<POIType>().select("name"))
                .stream().map(POIType::getName).collect(Collectors.toList());

        redisTemplate.opsForValue().set("POITypeNames", name);

        return name;
    }




}
